<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;

use App\Models\Identity;
use App\Models\UserIdentity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Exception;

class IdentityController extends Controller
{
    private $identity;
    private $request;

    public function __construct(Request $request)
    {
        $this->identity = new Identity();
        $this->request = $request;
    }
    public function identity()
    {
        $input = $this->request->all();
        if($this->request->isMethod('get'))
        {
            $validator = Validator::make($input, [
                'p_id' => 'required',
            ], [
                'p_id.required' => 'p_id必填',
            ]);
            if ($validator->fails()) {
                return $this->error($validator->errors()->first());
            }
            $field = ['id','name','p_id'];
            $data = $this->identity->getAllData(['p_id'=>$input['p_id']],$field);
            return $this->success($data);
        }else if($this->request->isMethod('post') || $this->request->isMethod('delete'))
        {
            $validator = Validator::make($input, [
                'identity_ids' => 'required|json',
            ], [
                'identity_ids.required' => 'identity_id必填',
                'identity_ids.json' => 'identity_id必须为json格式',
            ]);
            if ($validator->fails()) {
                return $this->error($validator->errors()->first());
            }
            $identity_ids = json_decode($input['identity_ids'],True);
            $userIdentity['user_id'] = getUserId();
            DB::beginTransaction();
            try{
                foreach ($identity_ids as $identity_id)
                {
                    $userIdentity['identity_id'] = $identity_id;
                    if($this->request->isMethod('post'))
                    {
                        $identity = $this->identity->getOne(['id'=>$identity_id]);
                        if($identity->p_id == 0)
                        {
                            throw new Exception('不能直接选择顶级身份: '.$identity->name);
                        }
                        $identityOnly = (new UserIdentity())->getOne($userIdentity);
                        if($identityOnly == null)
                        {
                            UserIdentity::create($userIdentity);
                        }
                    }else{
                        # 删除身份
                        UserIdentity::where($userIdentity)->delete();
                    }
                }
                DB::commit();
                return $this->success();
            }catch (Exception $e)
            {
                DB::rollBack();
                return $this->error($e->getMessage());
            }
        }
        return '为什么到这里来了呢?';
    }
}
